package javase.ch04;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * 初始化CyclicBarrier(2)（需 2 个线程到达屏障），
 * 线程 1 打印 A 后调用await()阻塞，线程 2 打印 B 后调用await()，两者都到达后屏障放行，线程 1 继续打印 C
 */
public class CyclicBarrierTest {
    public static void main(String[] args) {
        CyclicBarrier barrier = new CyclicBarrier(2); //计时器
        new Thread(()->{
            System.out.println("A");

            try {
                barrier.await(1, TimeUnit.SECONDS);//到达屏障，等待线程 2
            } catch (InterruptedException | BrokenBarrierException | TimeoutException e) {
                throw new RuntimeException(e);
            }
            System.out.println("C");
        },"线程1").start();
        new Thread(()->{
            System.out.println("B");
            try {
                barrier.await();//到达屏障，和线程1一起放行
            }  catch (InterruptedException | BrokenBarrierException e) {
                throw new RuntimeException(e);
            }
        },"线程2").start();

    }
}

